{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a88330d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "file = 'item4/wine-clean.data'\n",
    "names=['label','a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12','a13']\n",
    "dataset=pd.read_csv(file,names=names)\n",
    "\n",
    "#数据切片\n",
    "data =dataset.iloc[range(0,178),range(1,14)]\n",
    "target =dataset.iloc[range(0,178),range(0,1)].values.reshape(1,178)[0]\n",
    "print(f'特征数组的形状：{data.shape}')\n",
    "print(f\"特征数组的形状：{target.shape}\")\n",
    "\n",
    "\n",
    "from sklearn import preprocessing\n",
    "cdata=preprocessing.StandardScaler().fit_transform(data)\n",
    "print(cdata)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35c31d1a",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "#查找最优k值\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.neighbors import KNeighborsClassifier \n",
    "from sklearn.model_selection import train_test_split \n",
    "from sklearn.model_selection import cross_val_score\t\n",
    "x,y=cdata,target\n",
    "x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=0) \n",
    "\n",
    "#定义k值选值范围\n",
    "k_range=range(1,15)\t\n",
    "k_error=[]\t\n",
    "for k in k_range:\n",
    "   model=KNeighborsClassifier(n_neighbors=k)\n",
    "   scores=cross_val_score(model,x,y,cv=5,scoring='accuracy')\n",
    "   k_error.append(1-scores.mean())\n",
    "\n",
    "\n",
    "#绘制图版得到最优的k值\n",
    "plt.rcParams['font.sans-serif']='Simhei'\n",
    "plt.plot(k_range,k_error,'r-')\n",
    "plt.xlabel('k的取值')\n",
    "plt.ylabel('预测误差率')\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52808cc1",
   "metadata": {},
   "outputs": [],
   "source": [
    "#使用k值等于9来进行训练模型并评估\n",
    "from sklearn.metrics import accuracy_score\n",
    "\n",
    "model=KNeighborsClassifier(n_neighbors=9)\n",
    "model.fit(x_train,y_train)\n",
    "pred=model.predict(x_train,y_train)\n",
    "\n",
    "\n",
    "print (f'测试集的预测标签：{pred}')\n",
    "print(f'测试集的真实标签：{y_test}')\n",
    "\n",
    "ac =  accuracy_score(y_test,pred)\n",
    "print(f'模型预测准确率：{ac}')\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "AIG241",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.14.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
